package com.emisky.pictures.common;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class RequestWrapper {
	private HttpServletRequest request;
	private Map<String, String[]> paramsMap=new HashMap<String,String[]>();
	private Map<String ,FileItem> fileParamsMap=new HashMap<String, FileItem>();
	public RequestWrapper(HttpServletRequest request){
		this.request=request;
		this.init();
	}
	
	/**
	 * 获取参数值
	 * @param name
	 * @return
	 */
	public String getParameter(String name) {
		if(this.paramsMap.containsKey(name)){
			return this.paramsMap.get(name)[0];
		}
		return "";
	}
	
	
	public String getParameter(String name,String defaultValue){
		String value=this.getParameter(name);
		if(CommonUtils.isNullOrEmpty(value)){
			return defaultValue;
		}
		return value;
	}
	
	/**
	 * 获取多值
	 */
	public String[] getParameterValues(String name){
		if(this.paramsMap.containsKey(name)){
			return this.paramsMap.get(name);
		}
		return new String[]{};
	}
	
	/**
	 * 获取文件对象
	 * @param name
	 * @return
	 */
	public FileItem getFileParameter(String name){
		if(this.fileParamsMap.containsKey(name)){
			return this.fileParamsMap.get(name);
		}
		return null;
	}
	
	
	/**
	 * 获取参数的map
	 * @return
	 */
	public Map<String, String[]> getParameterMap() {
		return this.paramsMap;
	}
	/**
	 * 获取所有的文件
	 * @return
	 */
	public Map<String, FileItem> getFileParameterMap() {
		return this.fileParamsMap;
	}
	
	private void init(){
		this.paramsMap.putAll(this.request.getParameterMap());
		if(this.isMultipartContent()){
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload=new ServletFileUpload(factory);
				List<FileItem> items= upload.parseRequest(this.request);
				Iterator<FileItem> iterator=items.iterator();
				while (iterator.hasNext()) {
					FileItem item=iterator.next();
					if(item.isFormField()){
						this.paramsMap.put(item.getFieldName(), 
								new String[]{item.getString()});
					}else{
						this.fileParamsMap.put(item.getFieldName(), item);
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 判断是否为文件上传
	 * @return true为文件上传
	 */
	public boolean isMultipartContent() {
		return ServletFileUpload.isMultipartContent(this.request);
	}
	
	
    /** 
     * 获取当前网络ip 
     * @param request 
     * @return 
     */  
    public String getIpAddr(){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }  
	
}
